package com.example.backblog.controller.front.user;

import com.example.backblog.entity.user.User;
import com.example.backblog.repository.user.UserRepository;
import com.example.backblog.service.oauth.GiteeProviderService;
import com.example.backblog.service.oauth.dto.GiteeUser;
import com.example.backblog.service.oauth.dto.ProviderToken;
import com.example.backblog.vo.ApiResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@Controller
public class AccessTokenController {
    @Autowired
    private GiteeProviderService giteeProvider;

    @Value("${gitee.client_id}")
    private String clientId;

    @Value("${gitee.redirect_url}")
    private String redirectUri;

    @Value("${gitee.secret}")
    private String clientSecret;
    @Autowired
    private UserRepository userRepository;
    @GetMapping("/login/recall")
    public String recall(@RequestParam("code") String code,
                            @RequestParam("state") String state,
                            Model model) throws Exception {
        //用户授权信息
        ProviderToken token = new ProviderToken();
        token.setClientId(clientId);
        token.setRedirectUri(redirectUri);
        token.setClientSecret(clientSecret);
        token.setCode(code);
        token.setState(state);
        //获取token和登录的用户信息
        String accessToken = giteeProvider.getGiteeToken(token);
        GiteeUser giteeUser = giteeProvider.getGiteeUser(accessToken);

        // 查询用户是否存在，如果不存在则注册，如果存在则更新
        String username = giteeUser.getName();
        User user = userRepository.findFirstByNameEquals(username);
        if (user==null) {
            user = new User();
            user.setName(username);
            // 加密
            String salt = new SecureRandomNumberGenerator().nextBytes().toString();
            // 设置 hash 算法迭代次数
            int times = 2;
            // 得到 hash 后的密码
            String encodedPassword = new SimpleHash("md5", username, salt, times).toString();

            user.setSalt(salt);
            user.setPassword(encodedPassword);
            user.setType(1);
            user.setLastLogin(new Date());
            user.setUserPicture(giteeUser.getAvatar_url());
            userRepository.save(user);
        }else{
            user.setLastLogin(new Date());
            user.setUserPicture(giteeUser.getAvatar_url());
            userRepository.save(user);
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, username);
        try {
            // 设置session
            subject.login(usernamePasswordToken);
            return "redirect:/";
        } catch (AuthenticationException e) {
            throw new Exception("登录失败");
        }
    }
}
